package Day010_排序算法_异常.demo02_二分查找;

import java.util.Arrays;

public class Test1 {
    public static void main(String[] args) {
        int[] arr = {431, 54, 25, 25, 26, 45, 2, 4, 65, 3, 64, 6, 46, 7, 54};
        //冒泡排序
        for (int i = 0; i < arr.length - 1; i++) {
            for (int j = 0; j < arr.length - 1 - i; j++) {
                if (arr[j] > arr[j + 1]) {
                    int temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
            }
        }
        System.out.println(Arrays.toString(arr));
        //调用方法 查找元素2
        int index = getNum(arr, 2);
        if (index == -1) {
            System.out.println("没有找到");
        } else {
            System.out.println("找到了,索引为:" + index);
        }
        //调用方法 查找元素200
        int index1 = getNum(arr, 200);
        if (index1 == -1) {
            System.out.println("没有找到");
        } else {
            System.out.println("找到了,索引为:" + index1);
        }
    }

    //定义方法
    public static int getNum(int[] arr, int num) {
        //定义变量 表示左右索引
        int left = 0;
        int right = arr.length - 1;
        int index = -1;
        //循环
        while (left <= right) {
            //计算中间索引
            int mid = (left + right) / 2;
            //判断中间索引元素是否为要找的元素
            if (arr[mid] > num) {
                right = mid - 1;
            } else if (arr[mid] < num) {
                left = mid + 1;
            } else {
                index = mid;
                break;
            }
        }
        return index;
    }
}

